include ApplicationHelper
class LocalusersController < ApplicationController


  #control general de acceso cancan, segun los permisos definidos en ability.rb
  authorize_resource :resource => :localusers

  def selector_users_list
      @localusers = User.search_selector(params[:search_email], params[:page])
      render :partial=>'localusers/selector_users_list' , :locals => {:search_email => params[:search_email]}, :layout=>false
  end

  def selector_users_list_from_paginate
      @localusers = User.search_selector(params[:search_email], params[:page])
  end

  def redirect_back
      redirect_back_or_default params[:url]
  end

  # GET /localusers
  # GET /localusers.xml
  def index
    save_redirect_back request.request_uri
    search_email = params[:search_email] || ""
    @localusers = User.search(search_email, params[:page])
  end

  # GET /localusers/1
  # GET /localusers/1.xml
  def show
    @localuser = User.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @localuser }
    end
  end

  # GET /localusers/new
  # GET /localusers/new.xml
  def new
    @localuser = User.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => new_localuser_path(@localuser) }
    end
  end

  # GET /localusers/1/edit
  def edit
    @localuser = User.find(params[:id])
  end

  # POST /localusers
  # POST /localusers.xml
  def create

    respond_to do |format|

      #verifico si hay que enviar invitacion
      if params['send_invitation'] == 'yes'

          #controlo a mano si ya no existe un usuario con ese mail
          if User.count(:conditions => "upper(email) = upper('#{params[:user][:email]}')") > 0
            flash[:error] = t('devise.invitations.msg_email_taken')
            format.html { render :action => "new" }
            format.xml  { render :xml => @localuser.errors, :status => :unprocessable_entity }            
          else
            #limpiamos la contraseña porque no es valida
            params[:user][:password] = ""
            params[:user][:password_confirmation] = ""

            @localuser = User.new(params[:user])
            @localuser.password = nil
            @localuser.password_confirmation = nil

            #se genera el token para la invitacion
            @localuser.invitation_token = Devise.friendly_token
            @localuser.invitation_sent_at = Time.now.utc

            @localuser.save(false)

            #se crea la lista de favoritos del usuario
            WishList.create(:user => @localuser, :name => WishList::TYPE_FAVORITE, :type_list => WishList::TYPE_FAVORITE)

            #se crea el carrito de compras
            WishList.create(:user => @localuser, :name => WishList::TYPE_CART, :type_list => WishList::TYPE_CART)

            #se crea la lista de reservas
            WishList.create(:user => @localuser, :name => WishList::TYPE_RESERVE, :type_list => WishList::TYPE_RESERVE)

            #se envia la invitacion
            @localuser.send_invitation

            flash_message :notice, t('msg_record_successfully_created')
            flash_message :notice, t('devise.invitations.send_instructions')

            format.html { redirect_to(localuser_path(@localuser)) }
            format.xml  { render :xml => @localuser, :status => :created, :location => @localuser }
          end
      else
        
        @localuser = User.new(params[:user])
        if @localuser.save
          #se crea la lista de favoritos del usuario
          WishList.create(:user => @localuser, :name => "favoritos", :favorite => true, :create_date => Time.now)

          flash[:notice] = t('msg_record_successfully_created')
          format.html { redirect_to(localuser_path(@localuser)) }
          format.xml  { render :xml => @localuser, :status => :created, :location => @localuser }
        else
          format.html { render :action => "new" }
          format.xml  { render :xml => @localuser.errors, :status => :unprocessable_entity }
        end
      end
    end
  end

  # PUT /localusers/1
  # PUT /localusers/1.xml
  def update
    @localuser = User.find(params[:id])

    respond_to do |format|
      if @localuser.update_attributes(params[:user])

        flash[:notice] = t('msg_record_successfully_updated')
        format.html { redirect_to(localuser_path(@localuser)) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @localuser.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /localusers/1
  # DELETE /localusers/1.xml
  def destroy
    @localuser = User.find(params[:id])

    #control al borrar
    ok = true
    tables_violate_foreign_key = []
    if  !@localuser.contact.nil?
      tables_violate_foreign_key << t('activerecord.models.contact')
    end

    if tables_violate_foreign_key.size > 0
      ok = false
      flash[:error] = "#{t('lbl_error_delete_row_violate_foreign_key')} #{tables_violate_foreign_key.join(', ')}"
    end

    if ok
      @localuser.destroy
    end

    respond_to do |format|
      format.html { redirect_to(localusers_url) }
      format.xml  { head :ok }
    end
  end


end
